﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Web.Configuration;
using System.Data;
using System.IO;
using Common;
using Objects;
using BusinessLogicLayer.Manager;
using AutoFix.controls;
using AutoFix.ClientComponents;
using AutoFix.Base;
using System.Text;
namespace AutoFix

{
    public partial class create_article : BasePage
    {
        #region [Private Members]
        /// <summary>
        /// The article tags array
        /// </summary>
        private List<ArticleTag> articleTags = new List<ArticleTag>();
        /// <summary>
        /// stores the logged in user
        /// </summary>
        private User applicationUser = null;
        #endregion

        #region [Base Implementations]
        /// <summary>
        /// Gets or sets a value indicating whether [is login page].
        /// </summary>
        /// <value>
        ///   <c>true</c> if [is login page]; otherwise, <c>false</c>.
        /// </value>
        protected override bool IsLoginPage
        {
            get { return false; }
        }
        /// <summary>
        /// Gets or sets a value indicating whether [is anonymous page].
        /// </summary>
        /// <value>
        ///   <c>true</c> if [is anonymous page]; otherwise, <c>false</c>.
        /// </value>
        protected override bool IsAnonymousPage
        {
            get { return false; }
        }
        /// <summary>
        /// Page name
        /// </summary>
        protected override string PageName
        {
            get { return "Create Article"; }
        }

        /// <summary>
        /// Gets the authorized user types.
        /// </summary>
        protected override List<UserType> AuthorizedUserTypes
        {
            get { return new List<UserType>(new UserType[] { UserType.Admin, UserType.Contributor }); }
        }
        #endregion      

        #region [Event Handlers]
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {

            applicationUser = this.PageSession.ApplicationUser;
            if (!Page.IsPostBack)
            {
                ArticleTypeManager articleTypeManager = new ArticleTypeManager();
                List<ArticleType> articleTypes = null;
                if (!IsPostBack)
                {
                    try
                    {
                        articleTypes = articleTypeManager.GetArticleTypes();
                        foreach (ArticleType articleType in articleTypes)
                        {
                            ListItem item = new ListItem(articleType.ArticleTypeName, articleType.ArticleTypeID.ToString());
                            this.ddArticleType.Items.Add(item);
                        }
                    }
                    catch (Exception)
                    {

                        throw;
                    }
                    finally
                    {
                        articleTypeManager = null;
                        articleTypes = null;
                    }
                }
            }
        }
        /// <summary>
        /// Handles the click event of the creat article button.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnCreateArticle_Click(object sender, EventArgs e)
        {
            ArticleManager articleManager = new ArticleManager();
            Article article = new Article();
            List<Article> addedArticle = null;
            DateTime formattedDate = DateTime.Now;

            try
            {
                article.ArticleName = this.txtArticleName.Text.Trim();
                article.ArticleTypeID = Convert.ToInt32(this.ddArticleType.SelectedValue);
                article.VehicleModelID = Convert.ToInt32(this.hdnModelSelectedValue.Value);
                article.UserID = applicationUser.UserID;
                article.VehicleModelTypeID = Convert.ToInt32(this.hdnModelTypeSelectedValue.Value);
                article.VehicleModelTypeYearID = Convert.ToInt32(this.hdnModelTypeYearSelectedValue.Value);
                article.ArticleImageUrl = "";
                article.IsPublished = false;
                article.LastUpdatedDate = DateTime.Now.AddTicks(-(DateTime.Now.Ticks % TimeSpan.TicksPerSecond));
                article.IsActive = true;



                addedArticle = articleManager.UpdateArticleScalar(article);
                if (addedArticle != null && addedArticle.Count > 0)
                {
                    UpdateArticleImage(addedArticle[0]);
                    TagManager tagManager = new TagManager();
                    List<Tag> tagList = null;
                    List<Tag> tags = new List<Tag>();
                    Tag newTag = null;
                    List<Tag> addedList = null;
                    ArticleTag articleTag = null;
                    try
                    {
                        tagList = tagManager.GetTags();
                        string[] tagValues = this.hdnSelectedTag.Value.Split(',');
                        if (tagValues != null && tagValues[0] != string.Empty)
                        {
                            foreach (string tag in tagValues)
                            {
                                if (tag != string.Empty)
                                {
                                    int existTagID = GetExistingTagTagID(tagList, tag);
                                    if (existTagID > 0)
                                    {
                                        articleTag = new ArticleTag(); ;
                                        articleTag.ArticleID = addedArticle[0].ArticleID;
                                        articleTag.TagID = existTagID;
                                        articleTag.UserID = applicationUser.UserID;
                                        articleTag.IsActive = true;
                                        articleTags.Add(articleTag);
                                    }
                                    else
                                    {
                                        newTag = new Tag();
                                        newTag.TagName = tag;
                                        newTag.IsActive = true;
                                        tags.Add(newTag);
                                    }
                                }
                            }
                            addedList = tagManager.UpdateAllTagsScalar(tags);
                            if (addedList != null && addedList.Count > 0)
                            {
                                FillArticleTagsList(addedList, addedArticle[0].ArticleID);

                                ArticleTagManager articleTagManager = new ArticleTagManager();
                                string failedTags = string.Empty;
                                int counter = 0;
                                try
                                {
                                    foreach (ArticleTag aTag in articleTags)
                                    {
                                        bool success = articleTagManager.UpdateArticleTag(aTag);
                                        if (success != true)
                                        {
                                            this.pageActionMessage.InnerText = "Couldn't add one or more article tags";
                                            this.pageActionMessage.Attributes.Add("class", "error-msg");
                                        }
                                        else
                                        {
                                            counter = counter + 1;
                                        }

                                    }
                                    if (counter == articleTags.Count)
                                    {
                                        this.pageActionMessage.InnerText = "Article and tags were added successfully";
                                        this.pageActionMessage.Attributes.Add("class", "success-msg");
                                        this.btnAddSteps.Visible = true;
                                        this.PageSession.Article = addedArticle[0];
                                    }
                                }
                                catch (Exception)
                                {

                                    this.pageActionMessage.InnerText = "Couldn't add article tags";
                                    this.pageActionMessage.Attributes.Add("class", "error-msg");
                                }
                                finally
                                {
                                    articleTagManager = null;
                                }
                            }


                        }
                        else
                        {

                            this.pageActionMessage.InnerText = "Article was added successfully";
                            this.pageActionMessage.Attributes.Add("class", "success-msg");
                            this.btnAddSteps.Visible = true;
                            this.PageSession.Article = addedArticle[0];
                        }

                        
                    }
                    catch (Exception)
                    {

                        this.pageActionMessage.InnerText = "Failed to add the tags to the system";
                        this.pageActionMessage.Attributes.Add("class", "error-msg");
                    }
                    finally
                    {
                        tagManager = null;
                        tagList = null;
                        newTag = null;
                        tags = null;
                        addedList = null;
                        articleTag = null;
                    }
                }
                else
                {
                    this.pageActionMessage.InnerText = "Failed to add the article to the system";
                    this.pageActionMessage.Attributes.Add("class", "error-msg");
                }

            }
            catch (Exception)
            {
                this.pageActionMessage.InnerText = "Failed to add the article to the system";
                this.pageActionMessage.Attributes.Add("class", "error-msg");
            }
            finally
            {
                articleManager = null;
                article = null;
                this.txtArticleName.Text = "";
            }
        }
        #endregion

        #region [Web Methods]
        /// <summary>
        /// Gets the model type years
        /// </summary>
        /// <param name="vehicleModelTypeID">vehicleModelTypeID</param>
        /// <returns>serialized model type years</returns>
        [WebMethod]
        public static string GetModelTypeYears(string vehicleModelTypeID)
        {
            JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();
            List<KeyValuePair<string, string>> resultList = new List<KeyValuePair<string, string>>();
            VehicleModelTypeYearManager vehicleModelTypeYearManager = new VehicleModelTypeYearManager();
            List<VehicleModelTypeYear> vehicleModelTypeYears = null;
            string returnedString = string.Empty;

            try
            {
                vehicleModelTypeYears = vehicleModelTypeYearManager.GetVehicleModelTypeYears();
                foreach (VehicleModelTypeYear vehicleModelTypeYear in vehicleModelTypeYears)
                {
                    if (Convert.ToInt16(vehicleModelTypeID) == vehicleModelTypeYear.VehicleModelTypeYearID)
                    {
                        resultList.Add(new KeyValuePair<string, string>(vehicleModelTypeYear.VehicleModelTypeYearID.ToString(), vehicleModelTypeYear.VehicleYear.ToString()));

                    }

                }

                returnedString = jsonSerialize.Serialize(resultList);

            }
            catch
            {

            }
            finally
            {
                jsonSerialize = null;
                resultList = null;
                vehicleModelTypeYearManager = null;
                vehicleModelTypeYears = null;
            }
            return returnedString;
        }
        /// <summary>
        /// Gets the model type
        /// </summary>
        /// <param name="vehicleModelID">vehicleModelID</param>
        /// <returns>serialized model types</returns>
        [WebMethod]
        public static string GetModelTypes(string vehicleModelID)
        {

            JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();
            List<KeyValuePair<string, string>> resultList = new List<KeyValuePair<string, string>>();
            VehicleModelTypeManager vehicleModelTypeManager = new VehicleModelTypeManager();
            List<VehicleModelType> vehicleModelTypes = null;
            string returnedString = string.Empty;

            try
            {
                vehicleModelTypes = vehicleModelTypeManager.GetVehicleModelTypes();
                foreach (VehicleModelType vehicleModelType in vehicleModelTypes)
                {
                    if (Convert.ToInt16(vehicleModelID) == vehicleModelType.VehicleModelID)
                    {
                        resultList.Add(new KeyValuePair<string, string>(vehicleModelType.VehicleModelTypeID.ToString(), vehicleModelType.VehicleModelTypeName));

                    }

                }

                returnedString = jsonSerialize.Serialize(resultList);

            }
            catch
            {

            }
            finally
            {
                jsonSerialize = null;
                resultList = null;
                vehicleModelTypeManager = null;
                vehicleModelTypes = null;
            }
            return returnedString;
        }
        /// <summary>
        /// Gets the models
        /// </summary>
        /// <returns>serialized models</returns>
        [WebMethod]
        public static string GetAllModels()
        {
            JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();
            List<KeyValuePair<string, string>> resultList = new List<KeyValuePair<string, string>>();
            VehicleModelManager vehicleModelManager = new VehicleModelManager();
            List<VehicleModel> vehicleModels = null;
            string returnedString = string.Empty;

            try
            {
                vehicleModels = vehicleModelManager.GetVehicleModels();
                foreach (VehicleModel vehicleModel in vehicleModels)
                {
                    resultList.Add(new KeyValuePair<string, string>(vehicleModel.VehicleModelID.ToString(), vehicleModel.VehicleModelName));
                }

                returnedString = jsonSerialize.Serialize(resultList);

            }
            catch
            {
            }
            finally
            {
                jsonSerialize = null;
                resultList = null;
                vehicleModelManager = null;
                vehicleModels = null;
            }
            return returnedString;
        }
        /// <summary>
        /// Gets the tags
        /// </summary>
        /// <returns>serialized tags</returns>
        [WebMethod]
        public static string GetTags(){
            JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();
            List<KeyValuePair<int, string>> resultList = new List<KeyValuePair<int, string>>();
            TagManager tagManager = new TagManager();
            List<Tag> tags = null;
            string returnedString = string.Empty;

            try
            {
                tags = tagManager.GetTags();
                foreach (Tag tag in tags)
                {
                    resultList.Add(new KeyValuePair<int, string>(tag.TagID, tag.TagName));
                }

                returnedString = jsonSerialize.Serialize(resultList);

            }
            catch
            {
            }
            finally
            {
                jsonSerialize = null;
                resultList = null;
                tagManager = null;
                tags = null;
            }
            return returnedString;


        }     
        #endregion  
  
        #region [Private Methods]

        /// <summary>
        /// Adds the article image to folder and updates article
        /// </summary>
        /// <param name="addedArticle">added article</param>
        private void UpdateArticleImage(Article addedArticle)
        {
            ArticleManager articleManager = new ArticleManager();
            string fileName = string.Empty;
            string file = string.Empty;
            try
            {

                if (this.fleArticleImage.HasFile)
                {
                    if (this.fleArticleImage.PostedFile.ContentType == "image/jpeg")
                    {
                        Guid guid = Guid.NewGuid();
                        StringBuilder path = new StringBuilder();
                        path.Append(AppConfiguration.ArticlePath);
                        path.Append(addedArticle.ArticleID);

                        string pathToFile = path.ToString();
                        path = null;
                        string fileToStore = guid + ".jpg";

                        string completeDirectoryPath = Server.MapPath(pathToFile);
                        if (!Directory.Exists(pathToFile))
                        {
                            Directory.CreateDirectory(completeDirectoryPath);
                            completeDirectoryPath = Path.Combine(completeDirectoryPath, fileToStore);
                            if (!File.Exists(completeDirectoryPath))
                            {
                                file = completeDirectoryPath;
                                addedArticle.ArticleImageUrl = fileToStore;
                                this.fleArticleImage.SaveAs(file);
                            }
                        }
                    }
                    else
                    {
                        this.pageActionMessage.InnerText = "Invalid image file. Only jpg format is allowed";
                        this.pageActionMessage.Attributes.Add("class", "error-msg");
                        return;
                    }
                }
                else
                {

                    addedArticle.ArticleImageUrl = "";
                }
                bool success = articleManager.UpdateArticle(addedArticle);
                if (!(success))
                {

                    this.pageActionMessage.InnerText = "Failed to add the article image to the system";
                    this.pageActionMessage.Attributes.Add("class", "error-msg");
                }
            }
            catch (Exception)
            {

                this.pageActionMessage.InnerText = "Failed to add the article image to the system";
                this.pageActionMessage.Attributes.Add("class", "error-msg");
            }
            finally
            {
                articleManager = null;
            }

        }
        /// <summary>
        /// Gets the existing tag by tag id
        /// </summary>
        /// <param name="tagList">tagList</param>
        /// <param name="addedTag">addedTag</param>
        /// <returns>the tag id</returns>
        private int GetExistingTagTagID(List<Tag> tagList, string addedTag)
        {
            int tagID = 0;
            foreach (Tag tag in tagList)
            {
                if (tag.TagName == addedTag)
                {
                    tagID = tag.TagID;
                    break;
                }
            }
            return tagID;
        }
        /// <summary>
        /// Fills article tags list
        /// </summary>
        /// <param name="addedList">addedList</param>
        /// <param name="articleID">articleID</param>
        private void FillArticleTagsList(List<Tag> addedList, int articleID)
        {
            ArticleTag articleTag = null;
            foreach (Tag tag in addedList)
            {
                articleTag = new ArticleTag();
                articleTag.ArticleID = articleID;
                articleTag.TagID = tag.TagID;
                articleTag.UserID = applicationUser.UserID;
                articleTag.IsActive = true;
                articleTags.Add(articleTag);
            }
            articleTag = null;
        }
        #endregion

    }
}